import os
import sys
import re
import subprocess
import pandas as pd
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QLabel, QFileDialog, QTextBrowser, QSplitter, QDesktopWidget,  QHBoxLayout, QLineEdit, QCheckBox
from PyQt5.QtGui import QFont
import openpyxl

class CourseScheduleApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('课表自动生成工具v1.0')
        self.setGeometry(100, 100, 400, 200)
        self.setStyleSheet(
            "QMainWindow { background-color: #f0f0f0; }"
            "QWidget { font-family: '微软雅黑'; }"
        )
        font = QFont()
        font.setPointSize(14)
        self.setFont(font)

        # 获取屏幕的几何信息
        screen_geometry = QDesktopWidget().screenGeometry()
        # 计算窗口的位置使其居中
        window_width = self.frameGeometry().width()
        window_height = self.frameGeometry().height()
        x = (screen_geometry.width() - window_width) / 2
        y = (screen_geometry.height() - window_height) / 2
        self.move(int(x), int(y))

        # 设置mianWidget
        self.mainWidget = QWidget()
        self.setCentralWidget(self.mainWidget)
        self.mainLayout = QVBoxLayout()
        self.mainWidget.setLayout(self.mainLayout)

        # 编写代码UI
        self.maininfoLabel = QLabel('CSV文件批量合并工具',  self)
        self.maininfoLabel.setStyleSheet('color: #7171C6; font-size: 18px; font-weight: bold;')
        self.mainLayout.addWidget(self.maininfoLabel)

        # 浏览单个文件，以PPT为例
        self.browseButton = QPushButton('浏览PPT教材', self)
        self.browseButton.clicked.connect(self.BrowsePPT)
        # self.browseButton.setFixedSize(200, 30)  # 设置宽度为120，高度为40
        self.mainLayout.addWidget(self.browseButton)

        # 添加一个读取文件夹中所有文件的按钮
        self.openFolderButton = QPushButton('打开csv文件存放目录', self)
        self.openFolderButton.clicked.connect(self.open_csv_folder)
        self.mainLayout.addWidget(self.openFolderButton)

        # 添加输入框
        self.keywords = QLineEdit(self)
        self.keywords.setPlaceholderText("输入关键词，多个关键词以分号分隔")
        self.mainLayout.addWidget(self.keywords)

        # 添加一个打开文件保存目录的一个按钮
        self.openFolderButton = QPushButton('打开文件保存目录', self)
        self.openFolderButton.clicked.connect(self.open_save_folder)
        self.mainLayout.addWidget(self.openFolderButton)

        # 添加一个启动按钮
        self.startButton = QPushButton('启动', self)
        self.startButton.clicked.connect(self.mianstartExtraction)
        self.mainLayout.addWidget(self.startButton)

        # ResultTextEdit
        self.mainResultTextEdit = QTextBrowser(self)
        self.mainResultTextEdit.setOpenExternalLinks(True)
        self.mainLayout.addWidget(self.mainResultTextEdit)

    # 编写BrowsePPT函数
    def BrowsePPT(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        filePath, _ = QFileDialog.getOpenFileName(self, '选择PPT文件', '', 'PPT 文件 (*.pptx);;All Files (*)', options=options)
        if filePath:
            self.pptFilePath = filePath
            self.mainResultTextEdit.clear()
            # self.leftResultTextEdit.append(f'已选择的PPT文件: <a href="file:///{self.pptFilePath}">{self.pptFilePath}</a>')
            self.mainResultTextEdit.append(f'已选择的PPT文件: {self.pptFilePath}')

    # 编写open_csv_folder函数
    def open_csv_folder(self):
        # 打开文件夹
        folder_path = QFileDialog.getExistingDirectory(self)
        if folder_path:
            self.open_folder_path = folder_path
            self.mainResultTextEdit.append(f'已选择的CSV文件存放文件夹: {self.open_folder_path}')
        else:
            self.mainResultTextEdit.append('请选择文件夹！')

    def open_save_folder(self):
        # 打开文件夹
        folder_path = QFileDialog.getExistingDirectory(self)
        if folder_path:
            self.save_folder_path = folder_path
            self.mainResultTextEdit.append(f'已选择的结果保存文件夹: {self.save_folder_path}')
        else:
            self.mainResultTextEdit.append('请选择文件夹！')
            
    def mianstartExtraction(self):
        # if hasattr(self, 'pptFilePath', 'wordFilePath'):
        if hasattr(self, 'open_folder_path') and hasattr(self, 'save_folder_path'):
            self.mainResultTextEdit.append('\n文件处理中...')
            folder_path = CsvUtil(self.open_folder_path, self.save_folder_path).merge_csv()
            # self.rightResultTextEdit.append(f'\n输出文件夹: <a href="file:///{folder_path}">{folder_path}</a>')
            self.mainResultTextEdit.append(f'\n输出文件: {folder_path}')
        # 打开文件夹
            subprocess.Popen(['explorer', os.path.abspath(os.path.dirname(folder_path))], shell=True)  # Windows 上使用 "explorer"
        else:
            self.mainResultTextEdit.append('\n请先选择一个文件。')

class CsvUtil:
    def __init__(self, origin_folder_path, result_folder_path):
        self.origin_folder_path = origin_folder_path
        self.result_folder_path = result_folder_path
        # self.csv_files = [file for file in os.listdir(origin_folder_path) if file.endswith('.csv')]

    def merge_csv(self):

        csv_files = [file for file in os.listdir(self.origin_folder_path) if file.endswith('.csv')]
        merged_data = pd.read_csv(os.path.join(self.origin_folder_path, csv_files[0]))

        for file in csv_files[1:]:
            file_path = os.path.join(self.origin_folder_path, file)
            data_to_append = pd.read_csv(file_path)
            merged_data = pd.concat([merged_data, data_to_append], ignore_index=True)
        # 提取合并后的文件名，这里使用 csv_files[0]中的文件名
        merged_file_name = csv_files[0].split('.')[0] + '_merged'
        output_file = os.path.join(self.result_folder_path, merged_file_name+ ".csv")
        merged_data.to_csv(output_file, index=False)
        return output_file

    # 拆分文件成指定份数，返回拆分后的文件数，并在指定目录下生成拆分后的文件
    def split_csv(self, file_name, split_size):
        file_path = os.path.join(self.origin_folder_path, file_name)
        data = pd.read_csv(file_path)
        data_size = len(data)
        split_num = data_size // split_size
        if data_size % split_size != 0:
            split_num += 1
        for i in range(split_num):
            start = i * split_size
            end = start + split_size
            if i == split_num - 1:
                end = data_size
            split_data = data[start:end]
            output_file = os.path.join(self.result_folder_path, f"split_{i}.csv")
            split_data.to_csv(output_file, index=False)
        return split_num

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = CourseScheduleApp()
    mainWindow.show()
    sys.exit(app.exec_())
